package com.example.forestmanagement;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.example.forestmanagement.adapter.UserListAdapter;
import com.example.forestmanagement.model.UserInfo;
import com.example.forestmanagement.model.UserTrackPoint;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.content.SharedPreferences;

public class TrackPlaybackActivity extends AppCompatActivity {
    private static final String BASE_URL = "http://8.130.186.54:9898";
    private MapView mapView;
    private AMap aMap;
    private RecyclerView recyclerUsers;
    private UserListAdapter userAdapter;
    private List<UserInfo> userList = new ArrayList<>();
    private List<UserTrackPoint> trackPoints = new ArrayList<>();
    private List<LatLng> pathPoints = new ArrayList<>();
    
    private SeekBar seekbarProgress;
    private ImageButton btnPlay;
    private TextView tvSpeed;
    private TextView tvTime;
    private Button btnTimeSelect;
    private SearchView searchView;
    
    private Marker currentMarker;
    private Polyline trackLine;
    private boolean isPlaying = false;
    private int currentPointIndex = 0;
    private float playbackSpeed = 1.0f;
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable playbackRunnable;
    private OkHttpClient client = new OkHttpClient();
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
    private Button btnStart;
    private Button btnPause;
    private Button btnStop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track_playback);
        
        initViews();
        initMap(savedInstanceState);
        setupListeners();
        loadUserList();
        loadTrackData();
    }

    private void initViews() {
        mapView = findViewById(R.id.map_view);
        recyclerUsers = findViewById(R.id.recycler_users);
        seekbarProgress = findViewById(R.id.seekbar_progress);
        btnPlay = findViewById(R.id.btn_play);
        tvSpeed = findViewById(R.id.tv_speed);
        tvTime = findViewById(R.id.tv_time);
        btnTimeSelect = findViewById(R.id.btn_time_select);
        searchView = findViewById(R.id.search_view);
        btnStart = findViewById(R.id.btn_start);
        btnPause = findViewById(R.id.btn_pause);
        btnStop = findViewById(R.id.btn_stop);
        
        recyclerUsers.setLayoutManager(new LinearLayoutManager(this));
        userAdapter = new UserListAdapter(userList, this::onUserSelected);
        recyclerUsers.setAdapter(userAdapter);
        
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());
        
        btnStart.setOnClickListener(v -> startPlayback());
        btnPause.setOnClickListener(v -> pausePlayback());
        btnStop.setOnClickListener(v -> stopPlayback());
    }

    private void initMap(Bundle savedInstanceState) {
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
    }

    private void setupListeners() {
        btnPlay.setOnClickListener(v -> togglePlayback());
        
        seekbarProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    currentPointIndex = progress;
                    updateTrackDisplay();
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                filterUsers(query);
                return true;
            }
            
            @Override
            public boolean onQueryTextChange(String newText) {
                filterUsers(newText);
                return true;
            }
        });
    }

    private void loadUserList() {
        Request request = new Request.Builder()
                .url(BASE_URL + "/app-api/linban/user/list?jobGroupId=1")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(TrackPlaybackActivity.this, 
                        "加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getInt("code") == 0) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        List<UserInfo> newUserList = new ArrayList<>();
                        
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject item = data.getJSONObject(i);
                            UserInfo user = new UserInfo();
                            user.setId(item.getLong("id"));
                            user.setUserName(item.getString("userName"));
                            user.setUserAvatar(item.getString("userAvatar"));
                            user.setJob(item.getString("job"));
                            user.setJobGroup(item.getString("jobGroup"));
                            user.setIsAlive(item.getInt("isAlive"));
                            newUserList.add(user);
                        }

                        runOnUiThread(() -> {
                            userList.clear();
                            userList.addAll(newUserList);
                            userAdapter.notifyDataSetChanged();
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void onUserSelected(UserInfo user) {
        loadUserTrack(user.getId());
    }

    private void loadUserTrack(long userId) {
        Request request = new Request.Builder()
                .url(BASE_URL + "/app-api/linban/user-track/time-range?userId=" + userId)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(TrackPlaybackActivity.this, 
                        "加载轨迹失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getInt("code") == 0) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        List<UserTrackPoint> points = new ArrayList<>();
                        
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject item = data.getJSONObject(i);
                            UserTrackPoint point = new UserTrackPoint();
                            point.setId(item.getLong("id"));
                            point.setUserId(item.getLong("userId"));
                            point.setLatitude(item.getDouble("latitude"));
                            point.setLongitude(item.getDouble("longitude"));
                            point.setCreateTime(item.getLong("createTime"));
                            points.add(point);
                        }

                        runOnUiThread(() -> {
                            trackPoints = points;
                            prepareTrackPlayback();
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void prepareTrackPlayback() {
        if (trackPoints.isEmpty()) {
            Toast.makeText(this, "没有轨迹数据", Toast.LENGTH_SHORT).show();
            return;
        }

        // 清除之前的轨迹
        if (currentMarker != null) currentMarker.remove();
        if (trackLine != null) trackLine.remove();
        
        // 重置播放状态
        currentPointIndex = 0;
        isPlaying = false;
        btnPlay.setImageResource(android.R.drawable.ic_media_play);
        
        // 准备轨迹点
        pathPoints.clear();
        for (UserTrackPoint point : trackPoints) {
            pathPoints.add(new LatLng(point.getLatitude(), point.getLongitude()));
        }
        
        // 设置进度条
        seekbarProgress.setMax(trackPoints.size() - 1);
        seekbarProgress.setProgress(0);
        
        // 显示初始位置
        updateTrackDisplay();
        
        // 移动地图到轨迹范围
        if (!pathPoints.isEmpty()) {
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pathPoints.get(0), 15));
        }
    }

    private void updateTrackDisplay() {
        if (currentPointIndex >= trackPoints.size()) return;
        
        UserTrackPoint point = trackPoints.get(currentPointIndex);
        LatLng position = new LatLng(point.getLatitude(), point.getLongitude());
        
        // 更新标记位置
        if (currentMarker == null) {
            currentMarker = aMap.addMarker(new MarkerOptions()
                    .position(position)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker)));
        } else {
            currentMarker.setPosition(position);
        }
        
        // 更新轨迹线
        List<LatLng> displayPoints = pathPoints.subList(0, currentPointIndex + 1);
        if (trackLine != null) {
            trackLine.remove();
        }
        trackLine = aMap.addPolyline(new PolylineOptions()
                .addAll(displayPoints)
                .width(10)
                .color(Color.BLUE));
        
        // 更新时间显示
        tvTime.setText(timeFormat.format(new Date(point.getCreateTime())));
        seekbarProgress.setProgress(currentPointIndex);
    }

    private void togglePlayback() {
        if (isPlaying) {
            stopPlayback();
        } else {
            startPlayback();
        }
    }

    private void startPlayback() {
        if (trackPoints.isEmpty()) return;
        
        isPlaying = true;
        btnPlay.setImageResource(android.R.drawable.ic_media_pause);
        
        playbackRunnable = new Runnable() {
            @Override
            public void run() {
                if (currentPointIndex < trackPoints.size() - 1) {
                    currentPointIndex++;
                    updateTrackDisplay();
                    handler.postDelayed(this, (long) (1000 / playbackSpeed));
                } else {
                    stopPlayback();
                }
            }
        };
        
        handler.post(playbackRunnable);
    }

    private void stopPlayback() {
        isPlaying = false;
        btnPlay.setImageResource(android.R.drawable.ic_media_play);
        if (playbackRunnable != null) {
            handler.removeCallbacks(playbackRunnable);
        }
        currentPointIndex = 0;
        if (trackLine != null) {
            trackLine.remove();
            trackLine = null;
        }
        btnStart.setEnabled(true);
        btnPause.setEnabled(false);
        btnStop.setEnabled(false);
        
        // 重置相机位置
        if (!pathPoints.isEmpty()) {
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pathPoints.get(0), 15));
        }
    }

    private void pausePlayback() {
        isPlaying = false;
        btnPlay.setImageResource(android.R.drawable.ic_media_play);
        if (playbackRunnable != null) {
            handler.removeCallbacks(playbackRunnable);
        }
        btnStart.setEnabled(true);
        btnPause.setEnabled(false);
    }

    private void filterUsers(String query) {
        if (query.isEmpty()) {
            userAdapter.updateData(userList);
            return;
        }
        
        List<UserInfo> filteredList = new ArrayList<>();
        for (UserInfo user : userList) {
            if (user.getUserName().toLowerCase().contains(query.toLowerCase()) ||
                user.getJob().toLowerCase().contains(query.toLowerCase())) {
                filteredList.add(user);
            }
        }
        userAdapter.updateData(filteredList);
    }

    private void loadTrackData() {
        int userId = getIntent().getIntExtra("userId", 0);
        if (userId == 0) {
            Toast.makeText(this, "用户ID无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
        String token = sp.getString("token", "");
        
        // 获取24小时内的轨迹数据
        long endTime = System.currentTimeMillis();
        long startTime = endTime - 24 * 60 * 60 * 1000;
        
        String url = String.format("%s/app-api/linban/track/list?userId=%d&startTime=%d&endTime=%d",
                BASE_URL, userId, startTime, endTime);
                
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .get()
                .build();
                
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(TrackPlaybackActivity.this,
                        "加载轨迹失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getInt("code") == 0) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        List<LatLng> points = new ArrayList<>();
                        
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject point = data.getJSONObject(i);
                            points.add(new LatLng(
                                point.getDouble("latitude"),
                                point.getDouble("longitude")
                            ));
                        }
                        
                        runOnUiThread(() -> {
                            pathPoints.clear();
                            pathPoints.addAll(points);
                            if (!pathPoints.isEmpty()) {
                                // 移动到第一个点
                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pathPoints.get(0), 15));
                                btnStart.setEnabled(true);
                            } else {
                                Toast.makeText(TrackPlaybackActivity.this,
                                        "没有找到轨迹数据", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> Toast.makeText(TrackPlaybackActivity.this,
                            "解析轨迹数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        pausePlayback();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
} 